﻿{% extends 'base.html' %}
{% load staticfiles %}
{% load codalab_tags %}
{% load tz %}

{% block page_title %}Participants{% endblock page_title %}
{% block head_title %}Participants{% endblock %}

{% block extra_head %}
    <script src="{% static 'js/foundation/vendor/jquery.validate.min.js' %}"></script>
{% endblock %}

{% block content %}

<a href="{% url "competitions:view" pk=competition_id %}" class="pull-right" >Go Back to Competition Homepage</a>
{% if allow_organizer_teams %}
    <a href="{% url "create_org_team" competition_pk=competition_id %}" class="pull-middle btn btn-default" >Create Organizer Team</a>
    <a href="{% url "create_org_teams_from_csv" competition_pk=competition_id %}" class="pull-middle btn btn-default" >Upload Team CSV</a>
{% endif %}

<div class="participants">
    <h3>Teams</h3>
    {% if teams_enabled or allow_organizer_teams %}
{#        {% if not allow_organizer_teams %}#}
{#            {% if pending_teams %}#}
                {% for item in pending_teams %}
                    <div class="panel panel-default competitionUserBlock teamUserBlock_{{ item.id }}">
                        <div class="panel-heading">
                            <h3 class="panel-title">{{ item.name }}
                                <span class="participationStatus label label-{{ item.status.codename }}">
                                    {% if item.status.codename == 'pending' %}
                                        Team pending approval
                                    {% elif item.status.codename == 'approved' %}
                                        Team approved
                                    {% elif item.status.codename == 'denied' %}
                                        Team denied
                                    {% elif item.status.codename == 'deleted' %}
                                        Team deleted
                                    {% else %}
                                        Unknown Status
                                    {% endif %}
                                </span>
                            </h3>
                        </div>
                        <div class="panel-body">
                            {% if item.status.codename == 'denied' %}
                                <p class="text-danger">Reason: {{ item.reason }}</p>
                            {% endif %}
                            <form class="custom process_request form-participate" id="team_request_{{ item.id }}">{% csrf_token %}
                                <input type="hidden" name="team_id" value="{{ item.id }}"/>
                                <div class="row">
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="status">Status:</label>
                                            <select id="status" name="status" class="form-control">
                                                <option value="approved">Approve</option>
                                                <option value="denied">Deny</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-sm-8">
                                        <div class="form-group">
                                            <label for="reason">Reason:</label>
                                            <textarea id="reason" name="reason" class="form-control"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <input type="submit" class="btn btn-primary pull-right" value="Process"/>
                            </form>
                        </div>
                    </div>
                {% endfor %}
{#            {% endif %}#}
{#        {% endif %}#}
        {% if not team_list %}
             <p><em>There are no teams.</em></p>
        {% else %}
            <table class="resultsTable dataTable table table-striped table-bordered">
                <thead>
                    <tr>
                        {% for column in team_columns %}
                        <th>
                            <a href="?order={{column.name}}{% if direction == 'asc' and order == column.name %}&direction=desc{% endif %}">
                                {{column.label}} <i class="{% if order == column.name %}{% if direction == 'asc'%}fi-arrow-down{% else %}fi-arrow-up{% endif %}{% endif %} right"></i>
                            </a>
                        </th>
                        {% endfor %}
                    </tr>
                </thead>
                <tbody>
                    {% for team in team_list %}
                    <tr>
                        {% for column in team_columns %}
                        <td>
                            {% if column.label == "STATUS" %}
                                <span class="label label-{{team|get_item:column.name}}">
                                    {{team|get_item:column.name}}
                                </span>
                                {% if not allow_organizer_teams %}
                                    <button type="button"
                                            class="pull-right btn btn-danger btn-sm team_revoke_button button {% if team.status == "denied" %}hide{% endif %}"
                                            team_id="{{ team.pk }}">Revoke
                                    </button>
                                    <button type="button"
                                            class="pull-right btn btn-success btn-sm team_reinstate_button button {% if team.status == "approved" %}hide{% endif %}"
                                            team_id="{{ team.pk }}">Reinstate
                                    </button>
                                {% else %}
                                    <a href="{% url "edit_org_team" competition_pk=competition_id pk=team.pk %}" class="pull-right button btn-primary btn-xs">Edit</a>
                                    <button id="delete_team" class="pull-right button btn-danger btn-xs" onclick="confirm_team_delete({{ team.pk }})">Delete</button>
                                {% endif %}
                            {% else %}
                                {{ team|get_item:column.name }}
                            {% endif %}
                        </td>
                        {% endfor %}
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        {% endif %}
    {% endif %}
</div>
<div class="participants">
    <h3>Participants</h3>

{#    {% if not allow_organizer_teams %}#}
        {% if not object_list %}
            <p><em>There are no participants.</em></p>
        {% else %}
            {% if not teams_enabled or allow_organizer_teams %}
                {% for item in pending_participants %}
                    <div class="panel panel-default competitionUserBlock competitionUserBlock_{{ item.id }}">
                        <div class="panel-heading">
                            <h3 class="panel-title">{{ item.user.username }}
                                <span class="participationStatus label label-{{ item.status.codename }}">
                                {% if item.status.codename == 'pending' %}
                                    Participation pending approval
                                {% elif item.status.codename == 'approved' %}
                                    Participation approved
                                {% elif item.status.codename == 'denied' %}
                                    Participation denied
                                {% else %}
                                    Unknown Status
                                {% endif %}
                            </span>
                            </h3>
                        </div>
                        <div class="panel-body">
                            {% if item.status.codename == 'denied' %}
                                <p class="text-danger">Reason: {{ item.reason }}</p>
                            {% endif %}
                            <form class="custom process_request form-participate" id="process_request_{{ item.id }}">{% csrf_token %}
                                <input type="hidden" name="participant_id" value="{{ item.id }}"/>
                                <div class="row">
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label for="status">Status:</label>
                                            <select id="status" name="status" class="form-control">
                                                <option value="approved">Approve</option>
                                                <option value="denied">Deny</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-sm-8">
                                        <div class="form-group">
                                            <label for="reason">Reason:</label>
                                            <textarea id="reason" name="reason" class="form-control"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <input type="submit" class="btn btn-primary pull-right" value="Process"/>
                            </form>
                        </div>
                    </div>
                {% endfor %}
            {% endif %}

            <button type="button" data-toggle="modal" href="#message_all_modal" class="btn btn-primary">Send message to
                all participants?
            </button>

            <table class="resultsTable dataTable table table-striped table-bordered">
                <thead>
                <tr>
                    {% for column in columns %}
                        <th>
                            <a href="?order=
                                    {{ column.name }}{% if direction == 'asc' and order == column.name %}&direction=desc{% endif %}">
                                {{ column.label }} <i class="
                                    {% if order == column.name %}{% if direction == 'asc' %}fi-arrow-down{% else %}fi-arrow-up{% endif %}{% endif %} right"></i>
                            </a>
                        </th>
                    {% endfor %}
                </tr>
                </thead>
                <tbody>
                {% for participant in participant_list %}
                    <tr>
                        {% for column in columns %}
                            <td>
                                {% if column.label == "STATUS" %}
                                    <span class="label label-{{ participant|get_item:column.name }}">
                                    {{ participant|get_item:column.name }}
                                    </span>
{#                                    {% if not allow_organizer_teams %}#}
                                        <button type="button"
                                                class="pull-right btn btn-danger btn-sm revoke_button button {% if participant.status == "denied" %}hide{% endif %}"
                                                participant_id="{{ participant.pk }}">Revoke
                                        </button>
                                        <button type="button"
                                                class="pull-right btn btn-success btn-sm reinstate_button button {% if participant.status == "approved" %}hide{% endif %}"
                                                participant_id="{{ participant.pk }}">Reinstate
                                        </button>
{#                                    {% endif %}#}
                                {% else %}
                                    {{ participant|get_item:column.name }}
                                {% endif %}
                            </td>
                        {% endfor %}
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        {% endif %}
{#    {% endif %}#}
    {% if not has_chagrade_bot %}
        <button style="margin: 2.5vh 0 2.5vh 0;" id="enable_chagrade" class="btn btn-primary">Enable Chagrade Features</button>
    {% endif %}
    </div>
</div>
<div class="modal fade" id="message_all_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Email Participants</h4>
            </div>
            <div class="modal-body">
                <form class="form-participate" id="message-form">
                    <div class="form-group">
                        <input id="subject_input" type="text" placeholder="Subject" class="form-control">
                            <div class="alert alert-danger" id="subject-alert" role="alert">
                              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                              <span class="sr-only">Error:</span>
                              Enter subject.
                            </div>
                    </div>
                    <div class="form-group">
                        <textarea id="message_textarea" placeholder="Message" class="form-control"></textarea>
                            <div class="alert alert-danger" role="alert" id="message-alert">
                              <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                              <span class="sr-only">Error:</span>
                              Enter message.
                            </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button id="direct_message_participants_button" class="btn btn-primary">Send</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

{% endblock %}
<script type="text/javascript">
{% block js %}

    $('#enable_chagrade').on('click', function() {
        $.ajax({
            type: 'post',
            url: '/api/competition/{{ competition_id }}/enable_chagrade/',
            contentType: "application/json",
            dataType: 'json'
        })
            .done(function (data) {
                $('#enable_chagrade').addClass('disabled')
                alert('Chagrade features enabled for competition.')
            })
            .fail(function (response) {
                if (response) {
                    var data = JSON.parse(response.responseText);
                    alert(data.error)
                }
            })
    })

    var confirm_team_delete = function(team_pk) {
        if (confirm("Do you want to delete this team?")) {
            url = "{% url "delete_org_team" competition_pk=competition_id team_pk=0 %}"
            url = url.replace("0", team_pk)

            console.log(url)
            $.post(url)
                .success(function(data) {
                    location.reload();
                })
        }
    }

    var participant_status_update = function(status, reason, participant_id) {
        $.post(
            "{% url "competition-participation-status" pk=competition_id %}",
            {
                status: status,
                reason: reason,
                participant_id: participant_id
            })
        .error(function() {
            alert("Error updating privileges");
        })
        .success(function() {
            var reinstate_button = $(".reinstate_button[participant_id='" + participant_id + "']");
            var revoke_button = $(".revoke_button[participant_id='" + participant_id + "']");

            if(status=="denied") {
                revoke_button.addClass('hide');
                reinstate_button.removeClass('hide');
            } else {
                revoke_button.removeClass('hide');
                reinstate_button.addClass('hide');
            }

            reinstate_button.parent().children('.column_text').html(status);
        });
    }

    $(".revoke_button").click(function() {
        if(confirm("Really revoke privileges?")) {
            var status = "denied";
            var reason = "";
            var participant_id = $(this).attr('participant_id');

            participant_status_update(status, reason, participant_id);
        }
    });

    $(".reinstate_button").click(function() {
        if(confirm("Are you sure you want to reinstate this participant?")) {
            var status = "approved";
            var reason = "";
            var participant_id = $(this).attr('participant_id');

            participant_status_update(status, reason, participant_id);
        }
    });


    /* $("#process_request").validate(); */

    var ParticipateStatusText = { 'approved': 'Participation Approved',
                                  'denied': 'Participation Denied',
                                  'pending': 'Participation Pending',
                                  'unknown': 'Unknown' };
    var ParticipationReasonStyle = {'denied': 'color:red',
                                    'unknown': '',
                                    'pending': '',
                                    'approved': '' };

    /* attach a submit handler to the form */
    $(".form-participate").submit(function(event) {

        /* stop form from submitting normally */
        event.preventDefault();

        /* get some values from elements on the page: */
        var values = $(this).serialize();
        var fid = $(this).attr('id');

        if (fid.match('team_request_')) {
            /* Send the data using post and put the results in a div */
            request = $.ajax({
                url: "/api/competition/{{competition_id}}/team_status/",
                type: "post",
                dataType: "json",
                accept: {'json': "application/json" },
                data: values,
                success: function(response, textStatus, jqXHR) {
                    $('#'+fid).remove();
                    var data = $.parseJSON(response);

                    var pid = $('div.teamUserBlock_' + data.teamId + ' .participationStatus');


                    pid.text(TeamStatusText[data.status]);

                    if(data.reason) {
                       var reasontext = '<p style="' + TeamReasonStyle[data.status] + ';">Reason: ' + data.reason +'</p>';

                       pid.append(reasontext);
                   }

                },
                error: function(jsXHR, textStatus, errorThrown) {
                    alert("There was a problem processing this request for this competition.");;
                }
            });
        } else {
            /* Send the data using post and put the results in a div */
            request = $.ajax({
                url: "/api/competition/{{competition_id}}/participation_status/",
                type: "post",
                dataType: "json",
                accept: {'json': "application/json"},
                data: values,
                success: function (response, textStatus, jqXHR) {
                    $('#' + fid).remove();
                    var data = $.parseJSON(response);

                    var pid = $('div.competitionUserBlock_' + data.participantId + ' p.participationStatus');


                    pid.text(ParticipateStatusText[data.status]);

                    if (data.reason) {
                        var reasontext = '<p style="' + ParticipationReasonStyle[data.status] + ';">Reason: ' + data.reason + '</p>';

                        pid.append(reasontext);
                    }

                },
                error: function (jsXHR, textStatus, errorThrown) {
                    alert("There was a problem processing this request for this competition.");
                    ;
                }
            });
        }
    });

    // Send email to participants
    $('#direct_message_participants_button').click(function() {
        var subject = $("#subject_input").val();
        var body = $("#message_textarea").val();

        if(subject && body) {
            $('#direct_message_participants_button').text('Sending...').addClass('disabled')
            removeErrorMessage();

            $.post(
                "{% url 'competitions:competition_message_participants' competition_id=competition_id %}",
                {subject: subject, body: body}
            )
            .error(function() {
                alert("Error sending email");
                $('#direct_message_participants_button').text('Send').removeClass('disabled');
            })
            .success(function() {
                $('#direct_message_participants_button').text('Send').removeClass('disabled');
                $('.modal').modal('hide');
                $("#subject_input").val('');
                $('#message_textarea').val('');
                removeErrorMessage();
            });
        } else {
            if ( subject.length < 1 ) {
                $('#subject-alert').css({
                    "display": "block"
                });
            };
            if ( body.length < 1 ) {
                $('#message-alert').css({
                    "display": "block"
                });
            };

        };
    });

$( document ).ready(function() {
    $("#submit_button").click(function () {
        $('#id_csv_file').click();
    });
    $('#id_csv_file').change(function(){
        $('#choose-file').submit()
    })
});

    function removeErrorMessage(){
        $('#subject-alert').css({
            "display": "none"
        });
        $('#message-alert').css({
            "display": "none"
        });
    }

{% endblock js %}
</script>
